package com.utaedang.jesseclub.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.utaedang.jesseclub.Main;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * Downloads a file in a thread. Will send messages to the
 * Main activity to update the progress bar.
 */
public class DownloaderThread extends Thread
{
	// constants
	private static final int DOWNLOAD_BUFFER_SIZE = 4096;

	// instance variables
	private Main parentActivity;
	private String downloadUrl;
  
  /**
   * Instantiates a new DownloaderThread object.
   * @param parentActivity Reference to Main activity.
   * @param inUrl String representing the URL of the file to be downloaded.
   */
  public DownloaderThread(Main thisActivity, String inUrl)
  {
    downloadUrl = "";
    if(inUrl != null)
    {
      downloadUrl = inUrl;
    }
    parentActivity = thisActivity;
  }
  
  /**
   * Connects to the URL of the file, begins the download, and notifies the
   * Main activity of changes in state. Writes the file to
   * the root of the SD card.
   */
  @Override
  public void run()
  {
    URL url;
    URLConnection conn;
    int fileSize, lastSlash;
    long lastModified;
    String fileName;
    BufferedInputStream inStream;
    BufferedOutputStream outStream;
    File outFile;
    FileOutputStream fileStream;
    Message msg;
    
    // we're going to connect now
    msg = Message.obtain(parentActivity.activityHandler,
    		Main.MESSAGE_CONNECTING_STARTED,
        0, 0, downloadUrl);
    parentActivity.activityHandler.sendMessage(msg);
    
    try
    {
      url = new URL(downloadUrl);
      conn = url.openConnection();
      conn.setUseCaches(false);
      fileSize = conn.getContentLength();
      lastModified = conn.getLastModified();
      Log.d(this.getName(), ""+lastModified);
      // get the filename
      lastSlash = url.toString().lastIndexOf('/');
      fileName = "file.bin";
      if(lastSlash >=0)
      {
        fileName = url.toString().substring(lastSlash + 1);
      }
      if(fileName.equals(""))
      {
        fileName = "file.bin";
      }
      
      // notify download start
      int fileSizeInKB = fileSize / 1024;
      msg = Message.obtain(parentActivity.activityHandler,
          Main.MESSAGE_DOWNLOAD_STARTED,
          fileSizeInKB, 0, fileName);
      parentActivity.activityHandler.sendMessage(msg);
      
      // start download
      inStream = new BufferedInputStream(conn.getInputStream());
      // app 내부에 쓰기
      String dirName = GlobalContext.DB_PATH + "files";
      File targetdir = new File(dirName);
      if(!targetdir.isDirectory()){
    	  targetdir.mkdirs();
      }
      outFile = new File(GlobalContext.DB_PATH + "files/" + fileName);
      if(outFile.exists()){
    	 outFile.delete();
    	 outFile.createNewFile();
      }
      // app 외부에 쓰기
      //outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
      
      fileStream = new FileOutputStream(outFile);
      outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
      byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
      int bytesRead = 0, totalRead = 0;
      while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
      {
        outStream.write(data, 0, bytesRead);
        
        // update progress bar
        totalRead += bytesRead;
        int totalReadInKB = totalRead / 1024;
        msg = Message.obtain(parentActivity.activityHandler,
            Main.MESSAGE_UPDATE_PROGRESS_BAR,
            totalReadInKB, 0);
        parentActivity.activityHandler.sendMessage(msg);
      }
      
      outStream.close();
      fileStream.close();
      inStream.close();
      
      if(isInterrupted())
      {
        // the download was canceled, so let's delete the partially downloaded file
        outFile.delete();
      }
      else
      {
    	// notify file handling
    	msg = Message.obtain(parentActivity.activityHandler,
    	            Main.MESSAGE_FILEHANDLING_RUNNGING,
    	            0, 0, "");
    	parentActivity.activityHandler.sendMessage(msg);
    	
    	File targetDir = new File(GlobalContext.DB_PATH);
        File targetFile = new File(GlobalContext.DB_PATH + "files/" + fileName);
        Function.unzip(targetFile, targetDir);

        // notify completion
        msg = Message.obtain(parentActivity.activityHandler,
            Main.MESSAGE_DOWNLOAD_COMPLETE);
        parentActivity.activityHandler.sendMessage(msg);
      }
    }
    catch(MalformedURLException e)
    {
      String errMsg = "Error : 유효하지 않은 URL 입니다.";//parentActivity.getString(R.string.error_message_bad_url);
      msg = Message.obtain(parentActivity.activityHandler,
          Main.MESSAGE_ENCOUNTERED_ERROR,
          0, 0, errMsg);
      parentActivity.activityHandler.sendMessage(msg);
    }
    catch(FileNotFoundException e)
    {
      String errMsg = "Error : 요청하신 파일이 존재하지 않습니다.";//parentActivity.getString(R.string.error_message_file_not_found);
      msg = Message.obtain(parentActivity.activityHandler,
          Main.MESSAGE_ENCOUNTERED_ERROR,
          0, 0, errMsg);
      parentActivity.activityHandler.sendMessage(msg); 
    }
    catch(Exception e)
    {
      String errMsg = "Error : 에러가 발생하였습니다.";//parentActivity.getString(R.string.error_message_general);
      msg = Message.obtain(parentActivity.activityHandler,
          Main.MESSAGE_ENCOUNTERED_ERROR,
          0, 0, errMsg);
      parentActivity.activityHandler.sendMessage(msg); 
    }
  }
  
}
  
